<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 联盟促销
 */
namespace app\allwin\controller\home;
use app\common\facade\Inform;
use think\facade\Request;
use app\common\controller\Official;
use app\common\event\User;
use app\common\facade\WechatMp;
use app\allwin\model\AllwinUnmarket;
use app\allwin\model\AllwinUnmarketOrder;
use app\allwin\model\AllwinUnmarketStore;
use app\allwin\model\AllwinUnmarketBooking;
use app\allwin\model\AllwinUnmarketReward;
use app\allwin\model\AllwinUnmarketVerif;
use app\allwin\model\MchId;
use app\common\facade\WechatPay;
use app\allwin\model\AllwinStore;

class Unmarket extends Official{

    /**
     * 分享赚钱营销
     */
    public function index($id){
        if(request()->isAjax()){
            $data = [
                'id'                => input('post.id/d'),
                'member_miniapp_id' => $this->member_miniapp_id,
                'telphone'          => input('post.telphone/s','','htmlspecialchars'),
                'telname'           => input('post.telname/s','','htmlspecialchars'),
                'uid'               => $this->user->id,
            ];
            $validate = $this->validate($data,'Unmarket.order');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            //判断是否已购买过
            $order = AllwinUnmarketOrder::where(['member_miniapp_id' => $this->member_miniapp_id,'share_id' => $data['id'],'uid' => $this->user->id,'state' => 1])->count();
            if($order > 0){
                return json(['code'=>0,'msg'=>'您已下单,不允许重复下单']);
            }
            //判断是否邀请用户
            $ucode = model('SystemUser')->isInvite(User::getUcode());
            $data['share_uid'] = 0;
            if($ucode){
                if($this->user['id'] != $ucode){
                    $data['share_uid'] = $ucode;
                }
            }
            $order_no = $this->user->invite_code.order_no();
            $data['order_no'] = $order_no;
            $result =  AllwinUnmarketOrder::createOrder($data);
            if($result){
                $unorder['miniapp_id'] = $this->member_miniapp_id;
                $unorder['name']       = $result->title;
                $unorder['order_no']   = $order_no;
                $unorder['total_fee']  = $result->price*100;
                $unorder['notify_url'] = Request::root(true).'/api-'.$this->member_miniapp_id.'/4/allwin-unmarket-notify.html';
                $setting = model('AllwinConfig')->getConfig($this->member_miniapp_id);
                if ($setting->is_psp == 1) {
                    $mid = MchId::getMch(0,$this->member_miniapp_id);
                    $unorder['mchid']  = $mid->mchid;
                }
                $unorder['openid']     = $this->user->official_uid;
                $ispay = WechatPay::orderPay($unorder,true);
                if ($ispay['code'] == 0) {
                    return json(['code'=>0,'return_code'=>'FAIL','msg' => $ispay['msg']]);
                }
                return json(['code'=>200,'msg'=>'操作成功','data'=>$ispay['data']]);
            }else{
                return json(['code'=>0,'msg'=>'活动不存在']);
            }
        }else{
            $condition['id'] = $id;
            $info = AllwinUnmarket::where($condition)->find();
            if(empty($info)){
                $this->error("404 NOT FOUND");
            }
            $imgs = json_decode($info['imgs'],true);
            $info['imgs']        = array_values_unset($info->img,$imgs);
            $view['info']        = $info;
            $view['order']       = AllwinUnmarketOrder::where(['share_id' => $info->id,'state' => 1])->order('id desc')->select(); //订单
            $view['order_num']   = count($view['order']);
            $view['store']       = AllwinUnmarketStore::where(['union_id' => $info->id])->order('id desc')->select();  //好店
            $view['award_amout'] = AllwinUnmarketReward::where(['union_id' => $info->id])->sum('money');   //计算福利总金额
            $view['award']       = AllwinUnmarketReward::where(['union_id' => $info->id])->order('money desc')->limit(50)->select();  //福利排行榜
            $view['weconfig']    = WechatMp::jsApiList($this->member_miniapp_id);
            $view['post_url']    = urls('Allwin/unmarket/index',$this->member_miniapp_id,['id' =>$id,'ucode' => $this->ucode]);
            $view['share_url']   = urls('Allwin/unmarket/index',$this->member_miniapp_id,['id' =>$id,'ucode' => $this->user->invite_code]);
            $view['share_rcode'] = action("common/library/qrcode/create",['url' => $view['share_url'],'qrname'=>'unmarket_qrcode_'.$id.'_'.$this->user['invite_code']],'facade');
            AllwinUnmarket::where($condition)->setInc('views',rand(1,5));
            $this->view->engine->layout(false);
            return view()->assign($view);
        }
    }

    /**
     * 联盟商家
     */
    public function store(int $id,int $unid){
        $info = AllwinUnmarket::where(['id' => $unid])->field(['title,share_img,share_title,share_text'])->find();
        if(empty($info)){
            $this->error("404 NOT FOUND");
        }
        $store = AllwinUnmarketStore::where(['id' => $id,'union_id' => $unid])->find();
        if(empty($store)){
            $this->error("404 NOT FOUND");
        }
        $store->imgs         = array_values_unset($store->img,json_decode($store->imgs,true));
        $view['store']       = $store;
        $view['info']        = $info;
        $view['weconfig']    = WechatMp::jsApiList($this->member_miniapp_id);
        $view['share_url']   = urls('Allwin/unmarket/index',$this->member_miniapp_id,['id' =>$unid,'ucode' => $this->user->invite_code]);
        $this->view->engine->layout(false);
        return view()->assign($view);
    }


   /**
     * 我的订单
     */
    public function order(int $id){
        if (request()->isAjax()) {
            $data = [
                'id'                => $id,
                'store_id'          => input('post.store_id/d'),
                'member_miniapp_id' => $this->member_miniapp_id,
                'uid'               => $this->user->id,
            ];
            $validate = $this->validate($data,'Unmarket.okpass');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            //判断是否付款
            $order = AllwinUnmarketOrder::where(['uid' => $this->user->id,'share_id' => $id,'state' => 1])->count();
            if($order <= 0){
                return json(['code'=>0,'msg'=>'你没有下单,禁止核销']);
            }
            //判断是否联盟
            $store = AllwinUnmarketStore::where(['member_miniapp_id' => $this->member_miniapp_id,'union_id' => $id,'id' => $data['store_id']])->find();
            if(empty($store)){
                return json(['code'=>0,'msg'=>'未找到核销商家,禁止核销']);
            }
            //判断是否重复核销
            $verif = AllwinUnmarketVerif::where(['uid' => $this->user->id,'union_id' => $id,'store_id' => $data['store_id']])->count();
            if($verif > 0){
                return json(['code'=>0,'msg'=>'统一店铺,禁止重复核销']);
            }
            $verif_data['member_miniapp_id'] = $this->member_miniapp_id;
            $verif_data['uid']               = $this->user->id;
            $verif_data['union_id']          = $id;
            $verif_data['store_id']          = $data['store_id'];
            $verif_data['times']             = time();
            $rel = AllwinUnmarketVerif::insert($verif_data);
            if(empty($rel)){
                return json(['code'=>0,'msg'=>'核销失败']);
            }else{
                $modelStore = AllwinStore::where(['id' => $store->store_id])->find();
                if($modelStore){
                    //通知店主到微信
                    Inform::sms($modelStore->manage_uid,$this->member_miniapp_id,['title' =>'业务进展通知','type' => '订单核销','content' =>'您有新订单已经成功核销','state' => '成功']);
                }
                //通知申请者到微信
                Inform::sms($this->user->id,$this->member_miniapp_id,['title' =>'业务进展通知','type' => '订单核销','content' =>'您的订单已经成功核销','state' => '成功']);
                return json(['code'=>200,'msg'=>'您已成功核销']);
            }
        }else{
            $view['info'] = AllwinUnmarket::where(['id' => $id])->field(['id,telphone,mycode,tips,title,share_img,share_title,share_text,start_time,end_time'])->find();
            if(empty($view['info'])){
                $this->error("404 NOT FOUND");
            }
            $is_order = AllwinUnmarketOrder::where(['uid' => $this->user->id,'share_id' => $id,'state' => 1])->find();
            $order = [];
            if(empty($is_order)){
                $view['store'] = [];
            }else{
                $view['store'] = AllwinUnmarketStore::where(['member_miniapp_id' => $this->member_miniapp_id,'union_id' => $id])->select();

                $verif = AllwinUnmarketVerif::where(['uid' => $this->user->id,'union_id' => $id])->field('store_id')->select()->toArray();
                $order = array_column($verif,'store_id');
            }
            $view['order'] = $order;
            $this->view->engine->layout(false);
            return view()->assign($view);
        } 
    }

    /**
     * 联系客服
     */
    public function service(){
        if (request()->isAjax()) {
            $data = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'union_id'          => input('post.union_id/d', '', 'htmlspecialchars'),
                'name'              => input('post.storename/s', '', 'htmlspecialchars'),
                'telphone'          => input('post.telphone/s', '', 'htmlspecialchars'),
                'telname'           => input('post.telname/s', '', 'htmlspecialchars'),
            ];
            $validate = $this->validate($data, 'Unmarket.service');
            if (true !== $validate) {
                return json(['code'=>0,'msg'=>$validate]);
            }
            //读取所属活动
            $info = AllwinUnmarket::where(['id' => $data['union_id'],'member_miniapp_id' => $this->member_miniapp_id])->field('id')->find();
            if (empty($info)) {
                return json(['code'=>0,'msg'=>'活动不存在']);
            }
            $param = [
                'member_miniapp_id' => $this->member_miniapp_id,
                'union_id'          => $info->id,
                'store_name'        => $data['name'],
                'name'              => $data['telname'],
                'telphone'          => $data['telphone'],
            ];
            $result =  AllwinUnmarketBooking::edit($param);
            if ($result) {
                return json(['code'=>200,'msg'=>'我们客服会在8小时内与你联系']);
            } else {
                return json(['code'=>0,'msg'=>'提交错误,请重试']);
            }
        } else {
            $this->error('404 Not Found');
        }
    }
}